<template>
  <div class="page-box">
    <!-- <Header-Comp title="添加分店" /> -->
    <div class="header-box">
      <van-icon name="arrow-left" size="24" @click="goBack" />
      <div class="header-item">添加分店</div>
      <van-icon name="arrow-left" size="24" style="visibility: hidden" />
    </div>

    <div class="content-box">
      <van-form validate-first input-align="left" ref="form" @submit="nextStep">
        <van-cell-group>
          <van-field
            v-model="formData.phone"
            name="phone"
            label=""
            type="tel"
            placeholder="请输入手机号"
            @input="getAccountNo"
            :rules="phoneRules"
          >
            <template #left-icon>
              <van-icon class-prefix="iconfont icon-shouji" size="24" />
            </template>
          </van-field>
          <van-field
            v-model="formData.code"
            name="code"
            center
            clearable
            label=""
            type="digit"
            @input="change2"
            placeholder="请输入验证码"
            maxlength="6"
            :rules="[
              {
                required: true,
                message: '请输入验证码',
                trigger: 'onBlur',
              },
            ]"
          >
            <template #button>
              <van-button
                native-type="button"
                class="validate-btn"
                :disabled="codeBtn"
                @click="getValidCode"
                >{{ btnMessage }}{{ countDown }}</van-button
              >
            </template>
            <template #left-icon>
              <van-icon class-prefix="iconfont icon-yanzhengma" size="24" />
            </template>
          </van-field>

          <van-field
            v-model="formData.acconut"
            name="acconut"
            clearable
            label=""
            left-icon="contact"
            size="40"
            @input="change3"
            placeholder="请设置6-15字母或数字的账号"
            :rules="[
              {
                required: true,
                message: '请输入登录账号',
                trigger: 'onBlur',
              },
              {
                pattern: /^[a-zA-Z0-9]{6,15}$/,
                message: '账号错误，请重新设置6-15位登录账号',
                trigger: 'onChange',
              },
              {
                validator: asyncValidator,
                message: '账号已存在，请重新输入',
                trigger: 'onBlur',
              },
            ]"
          >
            <template #left-icon>
              <van-icon class-prefix="iconfont icon-zhanghao" size="24" />
            </template>
          </van-field>

          <van-field
            v-model="formData.passWord"
            name="passWord"
            clearable
            label=""
            :type="ispassword"
            size="40"
            @input="change4"
            placeholder="请设置6~15位数字+字母组合密码"
            :rules="[
              {
                required: true,
                message: '请输入登录密码',
                trigger: 'onBlur',
              },
              {
                pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/,
                message: '密码必须为6-15位字母+数字的随机组合',
                trigger: 'onChange',
              },
            ]"
          >
            <template #left-icon>
              <van-icon class-prefix="iconfont icon-mima" size="24" />
            </template>
            <template #right-icon>
              <van-icon
                class-prefix="iconfont icon-xianshi"
                size="24"
                v-if="showPass"
                @click="hidePassword"
              />
              <van-icon
                class-prefix="iconfont icon-buxianshi"
                size="24"
                v-else
                @click="showPassword"
              />
            </template>
          </van-field>
        </van-cell-group>

        <div class="fixed-box">
          <van-button
            :disabled="!hooked"
            color="#FFB72F"
            class="next-step-btn"
            native-type="submit"
            >下一步</van-button
          >
          <div class="protocol">
            <van-checkbox
              v-model="hooked"
              icon-size="18px"
              checked-color="#FFB72F"
            ></van-checkbox>
            <span
              >已阅读并同意<router-link
                :to="{
                  path: '/protocols',
                  query: {
                    deptId: $route.query.deptId || '1123598813738675201',
                  },
                }"
                >《门店注册及服务协议》</router-link
              >
            </span>
          </div>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import HeaderComp from "@/components/HeaderComps";
import { sendVerificationCode } from "@/api/register";
import { checkUserName, storeAdd, isBlacklist } from "@/api/merchant";
import { getSystemLimit } from "@/api/system";

export default {
  name: "Registers",
  components: {
    HeaderComp,
  },
  data() {
    return {
      checkUserName,
      formData: {
        phone: "",
        code: "",
        acconut: "",
        passWord: "",
      },
      checked: false,
      hooked: false,
      showPass: false,
      ispassword: "password",
      str: "88888888",
      countDown: "",
      btnMessage: "获取验证码",
      codeBtn: true,
      word1: false,
      word2: false,
      word3: false,
      word4: false,
      deptId: "",
      phoneRules: [
        {
          required: true,
          message: "请输入手机号",
          trigger: "onBlur",
        },
        {
          pattern: /^0?(13|14|15|16|17|18|19)[0-9]{9}$/,
          message: "手机号错误请重新输入11位手机号码",
          trigger: "onChange",
        },
        {
          validator: this.ValidatePhone,
          message: "暂不支持该手机号段，请更换其他号码重试",
          trigger: "onBlur",
        },
        {
          validator: this.checkBackList,
          message: "手机号填写失败，代码1000",
          trigger: "onBlur",
        },
      ],
    };
  },
  computed: {
    urlQuery() {
      return this.$store.state.user.urlQuery;
    },
    userInfo() {
      return this.$store.state.user.userInfo;
    },
  },
  watch: {
    formData: {
      handler(newV) {
        if (/^0?(13|14|15|16|17|18|19)[0-9]{9}$/.test(this.formData.phone)) {
          this.word1 = true;
        } else {
          this.word1 = false;
        }
        if (this.formData.code) {
          this.word2 = true;
        } else {
          this.word2 = false;
        }
        if (this.asyncValidator(this.formData.acconut)) {
          this.word3 = true;
        } else {
          this.word3 = false;
        }
        if (
          /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/.test(
            this.formData.passWord
          )
        ) {
          this.word4 = true;
        } else {
          this.word4 = false;
        }
        if (this.word1 && this.word2 && this.word3 && this.word4) {
          this.checked = true;
        } else {
          this.checked = false;
        }
      },
      deep: true,
    },
  },
  created() {
    let query = this.$route.query;
    this.deptId = query.deptId;
    if (query.merchantId) {
      this.$store.commit("setUrlQuery", query);
    }
    if (query.token) {
      localStorage.setItem("fuhuibatoken", query.token);
    }
    for (let key in this.formData) {
      this.formData[key] = "";
    }
  },
  beforeRouteLeave(to, from, next) {
    if (to.path == "/register") {
      document.title = "返回APP";
    } else {
      next();
    }
  },
  methods: {
    goBack() {
      this.$router.push({
        path: "/register",
      });
    },
    change2() {
      this.formData.code = this.formData.code.replace(/[^0-9]/g, "");
    },
    change3() {
      this.formData.acconut = this.formData.acconut.replace(
        /[^0-9a-zA-Z]/g,
        ""
      );
    },
    change4() {
      this.formData.passWord = this.formData.passWord.replace(
        /[^0-9a-zA-Z]/g,
        ""
      );
    },
    // 随机生成账号
    getAccountNo() {
      this.formData.phone = this.formData.phone.replace(/[^0-9]/g, "");
      if (this.formData.phone.length > 11) {
        this.formData.phone = this.formData.phone.substring(0, 11);
      }
      if (!/^0?(13|14|15|16|17|18|19)[0-9]{9}$/.test(this.formData.phone)) {
        this.codeBtn = true;
        return false;
      }
      checkUserName(this.formData.phone, this.deptId).then((res) => {
        if (res.code == 200) {
          this.formData.acconut = this.formData.phone;
        } else if (res.code == 400) {
          this.getSecondRandom();
        }
      });
    },
    getSecondRandom() {
      let letters = [
        "a",
        "b",
        "c",
        "d",
        "e",
        "f",
        "g",
        "h",
        "i",
        "j",
        "k",
        "l",
        "m",
        "n",
        "o",
        "p",
        "q",
        "r",
        "s",
        "t",
        "u",
        "v",
        "w",
        "x",
        "y",
        "z",
      ];
      function getRandomLetter(arr) {
        var idvalue = "";
        for (var i = 0; i < 2; i++) {
          idvalue += arr[Math.floor(Math.random() * 26)];
        }
        return idvalue;
      }
      let acconut = this.formData.phone + getRandomLetter(letters);
      checkUserName(acconut, this.deptId).then((res) => {
        if (res.code == 200) {
          this.formData.acconut = acconut;
        } else {
          this.getSecondRandom();
        }
      });
    },
    ValidatePhone(val) {
      if (/^0?(13|14|15|16|17|18|19)[0-9]{9}$/.test(val)) {
        return new Promise((resolve) => {
          getSystemLimit(this.deptId).then((res) => {
            let tel = val.substring(0, 3);
            let mobileBlackList = res.data.mobileBlackList;
            if (mobileBlackList.includes(tel)) {
              this.codeBtn = true;
            } else {
              if (this.btnMessage == "获取验证码") {
                this.codeBtn = false;
              }
            }
            resolve(!mobileBlackList.includes(tel));
          });
        });
      }
    },
    asyncValidator(val) {
      if (/^[a-zA-Z0-9]{6,15}$/.test(val)) {
        return new Promise((resolve) => {
          if (this.formData.phone.toString().length === 11) {
            checkUserName(val, this.deptId)
              .then((res) => {
                resolve(res.success);
              })
              .catch((err) => {
                resolve(err.success);
              });
          }
        });
      }
    },
    // 获取验证码
    getValidCode() {
      if (!/^0?(13|14|15|16|17|18|19)[0-9]{9}$/.test(this.formData.phone)) {
        this.$toast("请输入正确的手机号码");
        return false;
      }

      sendVerificationCode(
        this.formData.phone,
        this.$route.query.tenantId || "000001"
      ).then((res) => {
        if (res.code == 200) {
          this.$toast({
            type: "success",
            duration: 1500,
            message: "发送成功",
          });
          this.countDown = "S后获取";
          this.codeBtn = true;
          this.btnMessage = "60";
          let tiemerId = setInterval(() => {
            this.btnMessage--;
            if (this.btnMessage == 0) {
              clearInterval(tiemerId);
              this.codeBtn = false;
              this.btnMessage = "获取验证码";
              this.countDown = "";
            }
          }, 1000);
        }
      });
      let timer = setInterval(() => {
        if (typeof this.codeText == "number" && this.codeText != 0) {
          this.codeText--;
        }
        if (this.codeText == 0) {
          clearInterval(timer);
          this.codeText = "获取验证码";
        }
      }, 1000);
    },
    showPassword() {
      if (!this.formData.passWord) {
        return;
      }
      this.ispassword = "text";
      this.showPass = true;
    },
    hidePassword() {
      this.ispassword = "password";
      this.showPass = false;
    },
    nextStep() {
      if (!this.hooked) {
        this.$toast("请阅读并勾选协议");
        return false;
      }
      this.$toast({
        type: "loading",
        message: "正在提交...",
        forbidClick: true,
        duration: 0,
      });
      storeAdd({
        captcha: this.formData.code,
        mobile: this.formData.phone,
        password: this.formData.passWord,
        username: this.formData.acconut,
        merchantId: this.urlQuery.merchantId,
        deptId: this.urlQuery.deptId,
        // deptId: this.$route.query.deptId || "1123598813738675201",
        // merchantId: "1425001079832662017",
      })
        .then((res) => {
          console.log(res, "---");
          if (res.code == 200) {
            console.log(res, "111");
            this.$store.commit("setUserInfo", res.data);
            this.$store.dispatch("setStoreInfo", {
              id: res.data.id,
              tenantId: this.$route.query.tenantId || "000001",
            });
            this.$toast({
              type: "success",
              message: "注册成功",
              duration: 1500,
            });
            setTimeout(() => {
              this.$router.replace({
                path: "/step1",
              });
            }, 1500);
          } else if (res.code == 401) {
            this.$toast({
              type: "fail",
              message: res.message,
              forbidClick: true,
              duration: 2000,
            });
          } else {
            this.$toast({
              type: "fail",
              message: res.msg,
              forbidClick: true,
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          this.$toast({
            type: "fail",
            message: err,
            duration: 2000,
          });
        });
    },
    // 检查黑名单
    checkBackList(val) {
      return new Promise((resolve) => {
        isBlacklist(this.formData.phone).then(({ data }) => {
          this.phoneRules[3].message = data.consumerHotline
            ? `手机号填写失败，代码1000，请联系客服${data.consumerHotline}`
            : `手机号填写失败，代码1000`;
          resolve(!data.isBlacklist);
        });
      });
    },
  },
};
</script>
<style scoped lang="less">
@media (min-width: 320px) {
  .page-box {
    min-height: 568px;
    height: 100vh;
  }
}
/* iphone6 width:375; height:667*/
@media (min-width: 375px) {
  .page-box {
    min-height: 667px;
    height: 100vh;
  }
}
.page-box {
  min-height: 768px;
  height: 100vh;
}
.header-box {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}
.content-box {
  padding: 150px 60px 60px;
  height: 80%;
  box-sizing: border-box;
}
/deep/.van-field {
  border-bottom: 1px solid #d6d6d6;
  padding: 22px 10px;
}
/deep/.van-field__value {
  padding-left: 10px;
}
/deep/.van-hairline--top-bottom::after {
  border: none;
}
.next-step-btn {
  width: 80vw;
}
a {
  color: #ffb72f;
}
.protocol {
  display: flex;
  align-items: center;
  margin-top: 20px;
  margin-left: 10px;
  // position: fixed;
  // bottom: 101px;
  // left: 75px;
  span {
    margin-left: 10px;
    font-size: 26px;
  }
}

.validate-btn {
  width: 185px;
  height: 48px;
  line-height: 48px;
  border-radius: 24px;
  border: 1px solid #fdc53d;
  color: #fdc53d;
  font-size: 26px;
  box-sizing: border-box;
  padding: 12px 24px;
}
.header-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32px;
  border-bottom: 1px solid #d7d7d7;
  font-size: 36px;
  background: #fff;
  .header-item {
    font-weight: 500;
    color: #131313;
  }
}
.fixed-box {
  margin-top: 70%;
}
</style>
